/*
 * Copyright 2013-2020 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.cloud.gateway.filter;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import reactor.core.publisher.Mono;

import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.PooledDataBuffer;
import org.springframework.web.server.ServerWebExchange;

import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.CACHED_REQUEST_BODY_ATTR;

/**
 * RemoveCachedBodyFilter 是一个实现了 GlobalFilter 和 Ordered 接口的类。它的主要功能是在请求处理完成后，清理缓存的请求体数据，释放相关资源（如内存或缓冲区）。
 * 这是为了避免内存泄漏或资源占用问题。
 */
public class RemoveCachedBodyFilter implements GlobalFilter, Ordered {

	//功能: 定义日志对象，用于记录调试信息。
	//作用: 在清理缓存时记录相关信息，便于排查问题。
	private static final Log log = LogFactory.getLog(RemoveCachedBodyFilter.class);

	/**
	 * 功能: 核心过滤器逻辑，负责在请求处理完成后清理缓存的请求体数据。
	 *
	 * 使用 doFinally 方法，在请求处理完成后执行清理逻辑。
	 * doFinally 的回调函数会在无论成功还是失败的情况下都执行，确保资源清理的可靠性。
	 *
	 * 如果缓存的请求体是 PooledDataBuffer 类型，并且已分配资源，则开始释放。
	 * 调用 dataBuffer.release() 方法逐步释放资源：
	 * release() 方法会减少引用计数，直到引用计数为零时彻底释放资源。
	 * 使用 while 循环确保资源被完全释放。
	 *
	 * @param exchange the current server exchange
	 * @param chain provides a way to delegate to the next filter
	 * @return
	 */
	@Override
	public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
		return chain.filter(exchange).doFinally(s -> {
			Object attribute = exchange.getAttributes().remove(CACHED_REQUEST_BODY_ATTR);
			if (attribute != null && attribute instanceof PooledDataBuffer) {
				PooledDataBuffer dataBuffer = (PooledDataBuffer) attribute;
				if (dataBuffer.isAllocated()) {
					if (log.isTraceEnabled()) {
						log.trace("releasing cached body in exchange attribute");
					}
					// ensure proper release
					while (!dataBuffer.release()) {
						// release() counts down until zero, will never be infinite loop
					}
				}
			}
		});
	}

	@Override
	public int getOrder() {
		return HIGHEST_PRECEDENCE;
	}

}
